package com.imyours.message;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.Hibernate;
import org.hibernate.Session;

import com.imyours.model.message.MessageEntity;
import com.imyours.model.user.UserEntity;
import com.imyours.model.util.HibernateUtil;
import com.imyours.users.session.UserSessionManager;

public class MsgCenter {

	MsgCache msgCache = null;

	// 私有构造方法
	private MsgCenter() {
		msgCache = new MsgCache();
	}

	/**
	 * 获取未读的信息
	 * 
	 * @param user
	 * @return
	 */
	public List<MessageEntity> getMessage(UserEntity user) {
		List<MessageEntity> messageList = new ArrayList<MessageEntity>();

		messageList.addAll(msgCache.getMessage(user));
		Session se = HibernateUtil.getSessionFactory().openSession();
		List<MessageEntity> msgInDB = se.createQuery("from MessageEntity where reciver = ? ").setEntity(0, user).list();
		se.beginTransaction();
		for (int i = 0; i < msgInDB.size(); i++) {
			se.delete(msgInDB.get(i));
		}
		se.getTransaction().commit();
		se.close();
		messageList.addAll(msgInDB);
		return messageList;
	}

	/**
	 * 向某用户发送信息
	 * 
	 * @param msg
	 */
	public void sendMsg(MessageEntity msg) {
		if (UserSessionManager.getInstance().isOnline(msg.getReciver())) {
			msgCache.addMessage(msg);
		} else {
			Session se = HibernateUtil.getSessionFactory().openSession();
			se.beginTransaction();
			se.save(msg);
			se.getTransaction();
			se.close();
		}
	}

	// singleton
	private static MsgCenter singleton = null;

	public static MsgCenter getInstance() {
		if (singleton == null) {
			singleton = new MsgCenter();
		}
		return singleton;
	}
}
